package com.scujj.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scujj.mapper.OrderGoodsMapper;
import com.scujj.pojo.OrderGoods;
import com.scujj.pojo.Result;
import com.scujj.pojo.User;
import com.scujj.service.GoodsService;
import com.scujj.service.OrderGoodsService;
import com.scujj.service.UserService;
import com.scujj.util.PageUtil;
import com.scujj.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class OrderGoodsServiceImpl extends ServiceImpl<OrderGoodsMapper, OrderGoods> implements OrderGoodsService {
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserService userService;

    @Override
    public Result pageOrderByGuid(Page<OrderGoods> myPage, Long guid) {
        long current = myPage.getCurrent();
        long size = myPage.getSize();
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectOrderByGuid(guid, (current - 1) * size, size);
        Long total = orderGoodsMapper.countSelectOrderByGuid(guid);
        long page = total / size + 1;
        myPage.setRecords(orderGoodsList).setTotal(total).setPages(page);

        List<OrderGoods> orderList = orderGoodsSet(myPage.getRecords());

        return new PageUtil<OrderGoods>().objectPageOrder(myPage,orderList);
    }

    @Override
    public List<OrderGoods> orderGoodsSet(List<OrderGoods> orderList){
        if(!orderList.isEmpty()){
            orderList.forEach(order ->{
                order.setGoods(goodsService.getById(order.getGid()));
            });

            List<Long> ids = new LinkedList<>();
            orderList.forEach(order ->{
                ids.add(order.getGoods().getUid());
                ids.add(order.getUid());
            });

            List<User> userList= ResultUtil.listTrans(userService.getUserByIdList(ids).getData(),User.class);
            Map<Long,User> userMap= new HashMap<>();
            userList.forEach(user -> {
                userMap.put(user.getId(),user);
            });

            orderList.forEach(order ->{
                order.setUser(userMap.get(order.getUid()));
                order.getGoods().setUser(userMap.get(order.getGoods().getUid()));
            });
        }
        return orderList;
    }
}
